package day015.synchronizeddemo;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/8/3 0003
 */
public class AccountDemo {
    public static void main(String[] args) {

        //1 - 创建一个老公的线程
        Runnable r = new AccountThread();

        Thread husband = new Thread(r);
        husband.setName("文章:");

        Thread wife = new Thread(r);
        wife.setName("马伊琍:");
        husband.start();
        wife.start();
    }
}
class AccountThread implements Runnable{

    //临界资源...
    private Account acc = new Account();

    /**
     * 老公取款..
     * 老公完成取款,余额是:90
     * 老公取款..
     * 老公完成取款,余额是:80
     * 老婆取款..
     * 老婆完成取款,余额是:70
     * ...
     * ...
     *
     *
     * @param money
     */
    //同步代码的方式 - 不推荐的
//    public synchronized void withdraw(double money){
//        System.out.println(Thread.currentThread().getName()+"正在取款...");
//        acc.withdraw(money);
//
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(Thread.currentThread().getName()+",完成取款,余额是:"+acc.getMoney());
//    }

    //同步代码块 - 推荐
    public void withdraw(double money){
        synchronized (acc){//acc - 临界资源的对象.
            System.out.println(Thread.currentThread().getName()+"正在取款...");
            acc.withdraw(money);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+",完成取款,余额是:"+acc.getMoney());
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            withdraw(10);
        }
    }
}
